/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.orderoid.ejb.facade;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.orderoid.ejb.domain.Client;
import org.orderoid.ejb.exceptions.MetierException;
import org.orderoid.ejb.exceptions.TechniqueException;

/**
 *
 * @author Dahlia
 */
@Stateless
public class ClientFacade extends AbstractFacade<Client> {
    @PersistenceContext(unitName = "Orderoid-ejbPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public ClientFacade() {
        super(Client.class);
    }
    
    public Integer inscrire(Client entity) {
        getEntityManager().persist(entity);
        getEntityManager().flush();
        return entity.getIdClient();
    }
    
    public Client findByEmail(String email){
        Query query = em.createQuery("SELECT c FROM Client c WHERE c.email = :email");
        query.setParameter("email", email);
        List<Client> clients = query.getResultList();
        if(clients == null || clients.size() != 1){
            return null;
        }
        return (Client) query.getResultList().get(0);
    }
    
    public Client checkPassword(String identifiant, String password) 
            throws TechniqueException, MetierException{
        
        // On teste si les champs sont nulles
        if(identifiant == null || password == null){
            throw new TechniqueException("Veuillez remplir les champs obligatoires.");
        }
        //TODO
        // Récupération du client
        Client clientBase = findByEmail(identifiant);
        
        // On teste si le client existe et que le mot de passe est bon
        if(clientBase != null && clientBase.getPassword().equals(password)){
            return clientBase;
        }else{
            throw new MetierException("Le mot de passe ou l'identifiant est incorrect.");
        }
    }
}
